package com.hw01.mapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hw01.dto.TaskAllocationQueryDto;
import com.hw01.vo.TaskAllocationVo;
import org.apache.ibatis.annotations.Mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.github.yulichang.base.mapper.MPJJoinMapper;
import com.hw01.entity.TaskAllocation;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

/**
 * <p>
 * 分配任务 Mapper 接口
 * </p>
 *
 * @author zhong
 * @since 2024-03-18
 */
@Mapper
public interface TaskAllocationMapper extends BaseMapper<TaskAllocation>, MPJJoinMapper<TaskAllocation> {

    /**
     * 按条件查询分配任务信息(分页)
     * 
     * @param page 分页类
     * @param param 查询参数
     * @return 查询结果
     */
    @Select("<script>" +
            "select\n" +
            "    ta.id\n" +
            "    , e.id as user_id\n" +
            "    , e.user_name\n" +
            "    , ifnull(ta.year, #{param.year}) as year\n" +
            "    , ifnull(ta.month, #{param.month}) as month\n" +
            "    , ifnull(ta.workloads, 100) as workloads\n" +
            "    , ifnull(t3.confirmed_workloads, 0) as confirmed_workloads\n" +
            "    , ifnull(t3.committed_workloads, 0) as committed_workloads\n" +
            "from employee e\n" +
            "left join task_allocation ta\n" +
            "       on ta.del_state = 0\n" +
            "      and ta.year = #{param.year}\n" +
            "      and ta.month = #{param.month}\n" +
            "      and ta.user_id = e.id\n" +
            "left join (\n" +
            "    select\n" +
            "        user_id\n" +
            "        , sum(case when ew.leader_certain = 1 then ifnull(committed_workloads, 0) " +
            "           else 0 end) as confirmed_workloads\n" +
            "        , sum(ifnull(committed_workloads, 0)) as committed_workloads\n" +
            "    from employee_workloads ew\n" +
            "    where ew.del_state = 0\n" +
            "      and ew.year = #{param.year}\n" +
            "      and ew.month = #{param.month}\n" +
            "    group by user_id\n" +
            ") t3 on t3.user_id = e.id\n" +
            "where e.del_state = 0\n" +
            "  and e.use_state = 1\n" +
            "<if test='orgId != null'>" +
            "  and e.organization_id = #{orgId}\n" +
            "</if>" +
            "  and e.login_name != 'admin'\n" +
            "<if test='param.userName != null and param.userName != \"\"'>" +
            "  and e.user_name like concat('%' , #{param.userName} , '%')\n" +
            "</if>" +
            "order by t3.committed_workloads desc, e.id\n" +
            "</script>")
    IPage<TaskAllocationVo> selectTaskAllocationPage(IPage<TaskAllocationVo> page,
        @Param("param") TaskAllocationQueryDto param, @Param("orgId") Long orgId);

}
